define(["Zepto", 
        "underscore", 
        "mobiscroll",
        "Backbone", 
        "Handlebars",  
        "collections/orariocorsocollection",
        "collections/aulacollection",
        "text!templates/hall/searchhall.html",
        "views/hall/halllistview",
        "views/common/menuview"
], function($, _, mobiscroll, Backbone, Handlebars, OrariocorsoCollection, 
		AulaCollection, template, HallListView, MenuView) {
	
    var SearchHallView = Backbone.View.extend({
    	
        template: Handlebars.compile(template),
        render: function(eventName) {
            this.$el.html(this.template);
            
			// menu top
			this.menutop = new MenuView({
				el : $('#menu', this.el),
				model : this.model
			});
			this.menutop.render();
        	
        	
            return this;
        },

        postRender: function(eventName) {
            $('.dateNames').scroller({
                preset: 'select',
                theme: 'android-ics light',
                display: 'modal',
                mode: 'scroller'
            });

            $('.time').scroller({
                preset: 'time',
                theme: 'android-ics light',
                display: 'modal',
                mode: 'scroller',
                timeFormat: 'HH:ii',
                timeWheels: 'HHii',
                stepMinute: 15
            });

            $('.howlong').scroller({
                preset: 'select',
                theme: 'android-ics light',
                display: 'modal',
                mode: 'scroller'
            });
        },


        events: {
            'click #searchbutton': 'search',
            'touchstart .button': 'over',
            'touchend .button': 'left',
            'touchcancel .button': 'left',
            'touchstart button': 'over',
            'touchend button': 'left',
            'touchcancel button': 'left'
        },
        
   
        search: function(event) {

            var day = $('select.dateNames').val();
            var howl = $('select.howlong').val();
            var hour = $('input.time').val();

            var orainizioArray = hour.split(':');
            var oInizio = parseInt(orainizioArray[0]) + parseInt(orainizioArray[1])/60;
            var oFine = oInizio + parseFloat(howl);

            var orariocorsoCollection = new OrariocorsoCollection();
            var aulaCollection = new AulaCollection();
            orariocorsoCollection.fetch({
			   query : {
    				// Restituisco le aule occupate nell'orario specificato dall'utente (recuperando prima i corsi)
                    // if( (orainizio <= oInizio && orafine >= oFine) || (orainizio >= oInizio && orainizio <= oFine) )
    				weekday: day,
                    "$or":[{"orainizio" : {"$gte": oInizio, "$lte": oFine}},
                            {"orainizio" : {"$lte": oInizio} , "orafine" : {"$gte": oInizio}}]
                },
                success: function(data) {
                	aulaCollection.fetch({
                		
                		success:function(halls){
                			//alert(halls.length);
                			_.each(halls.models, function(hall) {
                			   // alert(' hall name: ' + hall.get('objectId'));

                			    _.each(data.models, function(ele) {
                					// alert('aula occupata:'+ele.aula.objectId);
                			    	if(ele.get('aula').objectId == hall.get('objectId')){
                			    			// alert('occupata ' + hall.get('nome') + ' dal corso ' + ele.get('objectId'));
                			    		 	halls.remove(hall);
                			    	}
                			    },this);
                		﻿  ﻿  ﻿  ﻿  
                		﻿  ﻿  ﻿  }, this);
                			
                			/*_.each(halls.models, function(h) {
                		    	alert('nome h lib ' + h.get('nome'));
                	﻿  ﻿  ﻿  }, this);*/
                			
                			
                			if(halls.length < 1){
                				alert('Non ci sono aule libere nell\' orario indicato');
                			}else{
                				
                				this.listView = new HallListView({
                					el: $('#list', this.el),
                					model : halls
                				});
                				this.listView.render();
                                // alert($('body').html());
                                //$('body').empty();
                                // $('body').append($(this.listView.el));
                                // alert($('body').html());
                                // this.listView.postRender(); //Va chiamato "a mano" perché non siamo in router.js che lo fa in automatico
                				return this;
                			}
                			
                		}
                	});
                },
                error: function (model, response) {
                    alert(response.responseText);
                }
			});
			
           
            
            
   
        },

        
        over: function(event) {
            $(event.currentTarget).addClass('fake-active');
        },

        left: function(event) {
            $(event.currentTarget).removeClass('fake-active');
        }
        
       
    });

    return SearchHallView;

});

